#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>

#define IMAGE_SIZE 176*144*3

#define BUFFER_SIZE 1000000
unsigned char* serial_buffer;

char* file_name;
int images_sent = 1; 

int save_bmp()
{
	FILE* f;
	char real_file_name[200];
	
	sprintf(real_file_name,"%s%d.bmp", file_name, images_sent++);
	printf("saving image %s ", real_file_name);	

	f = fopen(real_file_name, "wb");
	if(f == 0)
	{
		printf(" - failed\n");
		return 0;
	}
	// store bmp header
	char bmp_header[54] = {0x42,0x4d, 0,0,0,0, 0,0, 0,0, 54,0,0,0, 40,0,0,0, 176,0,0,0, 144,0,0,0, 1,0, 24,0, 0,0,0,0,  (char)(176*144*3)&0x0000ff,(char)((176*144*3)&0x00ff00)>>8,(char)((176*144*3)&0xff0000)>>16,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0 ,0,0,0};
	fwrite(bmp_header, 54, 1, f);
	// store data
	fwrite(serial_buffer, IMAGE_SIZE, 1, f);
	fclose(f);
	printf(" - succeded\n");
	return 1;
}

int main(int argc, char** argv)
{
	int images_sent = 0;

	if(argc<2)
    	{
        	printf("please specify filename\n");
		return 1;
    	}
	file_name = argv[1];

    	serial_buffer = (unsigned char*)malloc(BUFFER_SIZE);
    	if(serial_buffer==0)
    	{
		printf("unable to create buffer\n");
		return 1;
   	}

    	int serial_port = open("/dev/ttyS0", O_RDONLY|O_NOCTTY);
    	if(serial_port<0)
    	{
		printf("serial port:%d - error\n", serial_port);
		return 1;
    	}

      	struct termios serial_attributes;
	memset(&serial_attributes, 0, sizeof(serial_attributes));
    	serial_attributes.c_cflag = B115200 | CS8 | CLOCAL | CREAD | IGNPAR;
    	tcflush(serial_port, TCIFLUSH);
    	tcsetattr(serial_port, TCSANOW, &serial_attributes);

	printf("Serial Image Reciever\nBy Anders, Emil, Niklas and Philip\nKTH Robot08 (ras6)\n\nWaiting for data.\n");

	int buffer_counter = 0;

    	while(1)
     	{
	 	int bytes_read = read(serial_port, &serial_buffer[buffer_counter], BUFFER_SIZE);
	 	if(bytes_read == -1)
		{
			printf("communication error!\n");
		}
		else
		{
			buffer_counter += bytes_read;
			if(buffer_counter >= IMAGE_SIZE)
			{
				if(save_bmp() == 0) 
				{
					printf("system shutdown due to failed image store.\n");
				}
				if(buffer_counter > IMAGE_SIZE)
				{
					int i;
					int j = 0;
					for(i=IMAGE_SIZE; i<buffer_counter; i++)
						serial_buffer[j++] = serial_buffer[i];
					buffer_counter = j;
				}
				else buffer_counter = 0;
				printf("buffer_counter : %d", buffer_counter);
			}
		}

	}
	return 0;
}
